<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees'
import {
  addDepartments,
  getDepartmentsDetail,
  updateDepartments
} from '@/api/departments'
export default {
  props: {
    id: { type: String, required: true },
    isEdit: { type: Boolean, required: true },
    originList: { type: Array, required: true }
  },
  data() {
    // 验证部门编码是否重复
    const validCode = (rule, value, callback) => {
      // 当前的编码和父组件传过来的数组进行判断是否重复
      console.log(this.originList.map((item) => item.code))
      if (this.isEdit) {
        this.originList
          .filter((item) => item.id !== this.id)
          .map((item) => item.code)
          .includes(value)
          ? callback(new Error('部门编码' + value + '已被占用'))
          : callback()
      }
      this.originList.map((item) => item.code).includes(value)
        ? callback(new Error('部门编码' + value + '已被占用'))
        : callback()
    }
    // 验证部门名称是否重复
    const validName = (rule, value, callback) => {
      // 当前的名称和父组件传过来的数组进行判断是否重复
      console.log(
        this.originList
          .filter((item) => item.pid === this.id)
          .map((item) => item.name)
      )
      let existNameList = this.originList
        .filter((item) => item.pid === this.id)
        .map((item) => item.name)
      if (this.isEdit) {
        const pid = this.originList.find((item) => item.id === this.id).pid
        existNameList = this.originList
          .filter((item) => item.pid === pid) // 通过pid找到所有的兄弟，f11ter返回的是一个新的数组（所有的兄弟，包括自己）
          .filter((item) => item.id !== this.id) // 在所有的兄弟的新数组中，干掉自己，返回一个新的数组（所有的兄弟，排除了自己）
          .map((item) => item.name) // 使用map,获取只有包含name的数组
      }
      existNameList.includes(value)
        ? callback(new Error('此部门下已存在!' + value))
        : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      // 存储表单验证规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [{ required: true, message: '部门负责人不能为空' }],
        introduce: [
          { required: true, message: '部门介绍不能为空' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符' }
        ]
      },
      employees: []
    }
  },
  // watch: {
  //   id: function (new_value, old_value) {
  //     console.log(new_value, old_value)
  //     this.loadDepartmentsDetail()
  //   }
  // },
  created() {
    this.loadEmployeesSimple()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    }
    // this.qwq()
  },
  methods: {
    async loadDepartmentsDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        console.log('单个部门详情', res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    async loadEmployeesSimple() {
      try {
        const res = await getEmployeesSimple()
        console.log('获取员工简单列表', res.data)
        this.employees = res.data
      } catch (error) {
        console.log(error)
      }
    },
    qwq() {
      // 新增子部门
      let a = 1
      while (a < 100) {
        const form = {}
        form.name = '远哥最弔' + Math.floor(Math.random() * 10000)
        form.code = Math.floor(Math.random() * 10000)
        form.manager = '管理员'
        form.introduce = '..'
        console.log(form)
        const res = addDepartments({ ...form, pid: '' })
        console.log('qwq', res)
        a++
      }
    },
    async doAdd() {
      // 新增子部门
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res)
        this.$emit('success', res)
      } catch (error) {
        console.log(error)
      }
    },
    async doEdit() {
      // 编辑部门
      try {
        const res = await updateDepartments(this.id, this.form)
        console.log('修改', res)
        // 关闭对话框,刷新数据
        this.$emit('success', res)
      } catch (error) {
        console.log(error)
      }
    },
    // 确定
    hSubmit() {
      // 新增或编辑
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$emit('close')
    },
    resetForm() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>

<style>
</style>
